package com.ease.model.typehandler;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import org.springframework.jdbc.support.lob.LobHandler;
import org.springframework.orm.ibatis.SqlMapClientFactoryBean;

import com.ease.common.util.Assertion;
import com.ease.dao.jdbctemplate.core.NativeJdbcExtractorOracleLobHandler;
import com.ibatis.sqlmap.client.extensions.TypeHandlerCallback;

//extends BaseTypeHandler
// extends CustomTypeHandler

/**
 * 
 * @author nathanleewei
 * 
 */
public abstract class PgGeometryTypeHandler implements TypeHandlerCallback {

	// Cause: java.lang.ClassCastException:
	// com.mchange.v2.c3p0.impl.NewProxyConnection cannot be cast to
	// oracle.jdbc.OracleConnection
	// http://forums.oracle.com/forums/thread.jspa?threadID=1112428&tstart=1
	// - replaced the following code in nullSafeSet method from JGeometryType:
	//
	// OracleConnection connection = (OracleConnection)
	// preparedStatement.getConnection();
	//
	// with:
	//
	// C3P0NativeJdbcExtractor cp30NativeJdbcExtractor = new
	// C3P0NativeJdbcExtractor();
	// OracleConnection connection = (OracleConnection)
	// cp30NativeJdbcExtractor.getNativeConnection(preparedStatement.getConnection
	// ());
	private NativeJdbcExtractorOracleLobHandler nativeJdbcExtractorOracleLobHandler;

	public PgGeometryTypeHandler() {
		LobHandler lobHandler = SqlMapClientFactoryBean.getConfigTimeLobHandler();
		Assertion.notNull(lobHandler, "LobHandler not found");

		if (lobHandler instanceof NativeJdbcExtractorOracleLobHandler) {
			nativeJdbcExtractorOracleLobHandler = (NativeJdbcExtractorOracleLobHandler) lobHandler;
		}
	}

	protected Connection getOracleConnection(PreparedStatement ps) throws SQLException {
		if (null != nativeJdbcExtractorOracleLobHandler && null != nativeJdbcExtractorOracleLobHandler.getNativeJdbcExtractor()) {
			return nativeJdbcExtractorOracleLobHandler.getNativeJdbcExtractor().getNativeConnectionFromStatement(ps);
		} else {
			Connection conn = ps.getConnection();
			if (conn instanceof oracle.jdbc.OracleConnection) {
				return conn;
			} else {
				conn = conn.getMetaData().getConnection();
				if (conn instanceof oracle.jdbc.OracleConnection) {
					return conn;
				}
			}
		}
		return null;
	}
}
